<template>
  <div>
    <!-- 章节 -->
    <el-tree
      :data="data"
      ref="tree"
      node-key="id"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      :default-expand-all="true"
      icon-class="el-icon-s-promotion"
    >
      <span class="custom-tree-node" slot-scope="{ node }">
        <!-- 下面放状态，如果是完成就放完成，如果是进行就放进行，如果是未做就放未做的状态 -->
        <div
          class="node-box"
          :style="{
            color: node.data.id == currentSectionID ? '#409eff' : '#000',
          }"
        >
          <el-tooltip
            class="item"
            effect="dark"
            :content="getContent(node.data.status)"
            placement="top"
          >
            <img
              v-if="node.data.status == 1"
              class="status"
              src="images/done.png"
            />
            <img
              v-else-if="node.data.status == 0"
              class="status"
              src="images/doing.png"
            />
            <span
              v-else-if="node.data.status == -1"
              style="background: inherit"
              class="status"
            ></span>
          </el-tooltip>
          <span>{{ node.label }}</span>
        </div>
      </span>
    </el-tree>
  </div>
</template>

<script>
import { Loading } from "element-ui";
import PubSub from "pubsub-js";
import { mapState } from "vuex";
export default {
  name: "StudentChapter",
  data() {
    return {
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      isFirst: true,
    };
  },
  methods: {
    // 点击就会跳转
    handleNodeClick(data) {
      // console.log('node clicked')
      const { section_id } = this.$route.query;
      if (data.children) {
        return;
      }
      if (section_id == data.id) {
        return;
      }
      // 准备loading
      // const loading = Loading.service({
      //   lock: true,
      //   text: "Loading",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      this.$store.dispatch("studyAbout/getStudyContent", data.id);

      if (this.isFirst) {
        this.$router.push({
          path: "/study",
          query: {
            section_id: data.id,
          },
        });
        this.isFirst = false;
      } else {
        // 路由改变
        this.$router.replace({
          path: "/study",
          query: {
            section_id: data.id,
          },
        });
      }
    },
    getContent(status) {
      switch (status) {
        case -1:
          return "未完成";
        case 0:
          return "进行中";
        case 1:
          return "已完成";
        default:
          break;
      }
    },
    getIds() {
      let ids = [];
      this.data.forEach((obj) => {
        if (obj.children && obj.children.length > 0) {
          obj.children.forEach((item) => {
            ids.push(item.id);
          });
        }
      });
      return ids;
    },
    findPos(index) {
      let j = index;
      const arr = this.data.map((item) => item.children.length);
      // console.log(arr);
      for (let i in arr) {
        // if(j > a)
        if (j < arr[i]) {
          return { i, j };
        } else {
          j -= arr[i];
        }
      }
    },
  },
  created() {
    // 这一句报错
    // TODO:问题刷新过后那个currentCourseID就会消失
    // const { course_id } = this.props;
    // const course_id = localStorage.getItem("course_id");
    const { course_id } = this.$store.state.studyAbout.course;
    const { student_id } = JSON.parse(localStorage.getItem("userInfo"));

    this.pubId = PubSub.subscribe("finishSection", (msgName, data) => {
      const { i, j } = this.findPos(data);
      this.data[i].children[j].status = 1;
    });

    this.$http
      .get(
        `${this.$reqPrefix}/chapter?course_id=${course_id}&student_id=${student_id}`
      )
      .then((res) => {
        this.data = res.data.data.data || [];
        this.$store.commit("studyAbout/SET_SECTIONS", this.getIds());
      });
  },
  computed: {
    ...mapState("studyAbout", {
      currentSectionID: (state) => state.currentSection.id,
    }),
  },
  beforeDestroy() {
    PubSub.unsubscribe(this.pubId);
  },
};
</script>

<style lang="less" scoped>
ul {
  margin: 0;
  padding: 0;
}

.el-tree {
  .custom-tree-node {
    .node-box {
      // height: 100%;
      display: flex;
      align-items: center;
      color: #131b26;
      .status {
        margin-right: 10px;
        width: 24px;
        height: 24px;
      }
    }
  }
  :deep(.el-tree-node__content) {
    height: 48px;
  }
}
.highlight {
  background-color: #f0f7ff;
}
</style>